package com.mdd.admin.controller.refund;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.mdd.admin.service.finance.IFinanceService;
import com.mdd.admin.vo.finance.FinanceVo;
import com.mdd.common.entity.order.Order;
import com.mdd.common.entity.refund.OrderRefund;
import com.mdd.common.entity.user.User;
import com.mdd.common.enums.OrderRefundStatusEnum;
import com.mdd.common.enums.OrderStatusEnum;
import com.mdd.common.mapper.user.UserMapper;
import com.mdd.common.utils.TimeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @ClassName FinanceController
 * @Description
 * @Autore Slien.zuo
 * @Date 2022/10/13 19:17
 * @Version 1.0
 **/
@Api(tags = "财务中心")
@RestController
@RequestMapping("api/finance")
public class FinanceController {

    @Resource
    private IFinanceService financeService;

    @Resource
    private UserMapper userMapper;

    @GetMapping("/statistics")
    @ApiOperation(value = "财务中心 - 经营中心")
    public FinanceVo statisticsFinance() {
        return financeService.statisticsFinance();
    }

    @ApiOperation("财务中心 - 下载excel")
    @GetMapping("/downloadFinance")
    public void downloadFinance(@RequestParam Map<String, String> map, HttpServletResponse response) throws IOException {
        ExcelWriter writer = ExcelUtil.getWriter(true);
        Map<String, Object> orderListByCondition = financeService.getOrderListByCondition(map);
        HashMap<Long, String> userDetail = new HashMap<>();
        List<Order> orders = (List<Order>) orderListByCondition.get("orders");
        List<Map<String, Object>> collect = orders.stream().map(item -> {
            Map<String, Object> maps = new HashMap<>();
            maps.put("sn", item.getSn());
            User user = userMapper.selectById(item.getId());
            String userName = "";
            if(Objects.isNull(user)) {
                userDetail.put(item.getUserId(), "");
            } else {
                userName = user.getNickname();
                maps.put("userName", userName);
                userDetail.put(item.getUserId(), userName);
            }
            maps.put("userName", userName);
            maps.put("orderStatusName", OrderStatusEnum.getDesc(item.getOrderStatus()));
            maps.put("totalAmount", item.getTotalAmount());
            maps.put("totalNum", item.getTotalNum());
            maps.put("createTime", TimeUtil.timestampToDate(item.getCreateTime()));
            return maps;
        }).collect(Collectors.toList());
        writer.addHeaderAlias("sn", "订单编号");
        writer.addHeaderAlias("userName", "用户名称");
        writer.addHeaderAlias("orderStatusName", "订单状态");
        writer.addHeaderAlias("totalNum", "订单数量");
        writer.addHeaderAlias("totalAmount", "订单金额");
        writer.addHeaderAlias("createTime", "创建时间");

        writer.setColumnWidth(0, 30);
        writer.setColumnWidth(1, 30);
        writer.setColumnWidth(2, 30);
        writer.setColumnWidth(3, 30);
        writer.setColumnWidth(4, 30);
        writer.setColumnWidth(5, 30);
        writer.renameSheet(0, "订单页");
        writer.write(collect, true);


        writer.setSheet(1);
        List<OrderRefund> orderRefunds = (List<OrderRefund>) orderListByCondition.get("orderRefunds");
        List<Map<String, Object>> collect1 = orderRefunds.stream().map(item -> {
            Map<String, Object> maps = new HashMap<>();
            maps.put("sn", item.getSn());
            if (userDetail.containsKey(item.getUserId())) {
                maps.put("userName", userDetail.get(item.getUserId()));
            } else {
                User user = userMapper.selectById(item.getId());
                String nickname = "";
                if (Objects.isNull(user)) {
                    userDetail.put(item.getUserId(), "");
                } else {
                    nickname = user.getNickname();
                    maps.put("userName", nickname);
                    userDetail.put(item.getUserId(), nickname);
                }
                maps.put("userName", nickname);
            }
            maps.put("refundStatusName", OrderRefundStatusEnum.getEnum(item.getRefundStatus()));
            maps.put("orderAmount", item.getOrderAmount());
            maps.put("refundAmount", item.getRefundAmount());
            maps.put("createTime", TimeUtil.timestampToDate(item.getCreateTime()));
            return maps;
        }).collect(Collectors.toList());
        writer.addHeaderAlias("sn", "订单编号");
        writer.addHeaderAlias("userName", "用户名称");
        writer.addHeaderAlias("refundStatusName", "退款状态");
        writer.addHeaderAlias("orderAmount", "订单金额");
        writer.addHeaderAlias("refundAmount", "退款金额");
        writer.addHeaderAlias("createTime", "创建时间");

        writer.setColumnWidth(0, 30);
        writer.setColumnWidth(1, 30);
        writer.setColumnWidth(2, 30);
        writer.setColumnWidth(3, 30);
        writer.setColumnWidth(4, 30);
        writer.setColumnWidth(5, 30);
        writer.renameSheet(1, "退款页");
        writer.write(collect1, true);


        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("金额记录表-" + DateUtil.today() + ".xls", "utf-8"));
	    ServletOutputStream out = response.getOutputStream();
	    writer.flush(out, true);
        writer.close();
        IoUtil.close(out);
    }

    @ApiOperation("财务中心 - 月，季，年统计财务")
    @PostMapping("/conditionStatisticsFinance")
    public FinanceVo conditionStatisticsFinance(@RequestBody HashMap<String, String> map) {
        return financeService.conditionStatisticsFinance(map);
    }

}
